package com.sdu.rpc.client;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

import com.sdu.rpc.server.RpcRequest;

public class RpcProxy {

	private static String ip = "127.0.0.1";

	private static int port = 9999;

	@SuppressWarnings("unchecked")
	public static <T> T newInstance(Class<T> clazz) {

		InvocationHandler invocationHandler = new InvocationHandler() {

			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Socket socket = null;

				OutputStream outputStream = null;
				InputStream inputStream = null;

				System.out.println(proxy.getClass());
				System.out.println(method);
				System.out.println(args);
				
				try {
					socket = new Socket(ip, port);
					outputStream = socket.getOutputStream();
					RpcRequest rpcRequest = new RpcRequest();
					rpcRequest.setClassName(clazz.getName());
					rpcRequest.setMethodName(method.getName());
					rpcRequest.setParameters(args);
					ObjectOutputStream oos = new ObjectOutputStream(outputStream);
					oos.writeObject(rpcRequest);
					inputStream = socket.getInputStream();
					ObjectInputStream ois = new ObjectInputStream(inputStream);
					Object result = ois.readObject();
					return result;
				} finally {
					if (outputStream != null) {
						outputStream.close();
					}
					if (inputStream != null) {
						inputStream.close();
					}
					if (socket != null) {
						socket.close();
					}
				}
			}

		};

		return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz }, invocationHandler);

	}

}
